// 拨号工具类
import 'package:audio_test/core/utils/index.dart';
import 'package:flutter/services.dart';

/// 拨号工具类
/// 通过Flutter MethodChannel调用原生Android拨号功能
class Dialer {
  /// 方法频道名称
  // ignore: constant_identifier_names
  static const String DIALER_CHANNEL = "dialer";

  /// 用于与原生代码通信的MethodChannel
  static const MethodChannel _channel = MethodChannel(DIALER_CHANNEL);

  static const String _makePhoneCallMethod = "dial";

  /// 拨打电话号码
  ///
  /// 通过MethodChannel调用原生Android拨号功能
  /// 原生代码会处理权限检查和请求
  ///
  /// [phoneNumber] 需要拨打的电话号码
  /// 返回是否成功发起拨号请求
  static Future<bool> makePhoneCall(String phoneNumber) async {
    try {
      // 请求电话权限
      bool hasPermission = await RequestPermission.requestPhonePermission();

      if (!hasPermission) {
        return false;
      }

      // 通过MethodChannel调用原生拨号功能
      final bool? success = await _channel.invokeMethod(
        _makePhoneCallMethod,
        phoneNumber,
      );
      return success ?? false;
    } on PlatformException catch (e) {
      // 捕获平台异常
      print('拨号失败: ${e.message}');
      return false;
    } catch (e) {
      // 捕获其他异常
      print('拨号异常: $e');
      return false;
    }
  }
}
